package com.example.baseutils.usb;

import android.app.Application;
import android.content.IntentFilter;
import android.hardware.usb.UsbManager;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

/**
 * Author by lp,on 2021/12/21/021,15:32.
 */
public class UsbState {
    private static final String TAG = "UsbState";
    private boolean isInit = false;
    private List<UsbStateListtenr> listtenrList = new ArrayList<UsbStateListtenr>();
    private UsbChangeReceiver UsbChangeReciver = new UsbChangeReceiver(listtenrList);

    private static class Inner {
        private static UsbState inner = new UsbState();
    }

    private void UsbState() {
    }

    public static UsbState getInstance() {
        return Inner.inner;
    }

    //初始化，使用Application 避免内存泄露
    public void init(Application application) {
        if (isInit)
            return;
        isInit = true;
        //添加网络改变时的监听
        IntentFilter filter = new IntentFilter();
        filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
        filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
        application.registerReceiver(UsbChangeReciver, filter);

    }

    public void addListtner(UsbStateListtenr listtenr) {
        if (!isInit) {
            return;
        }
        if (!listtenrList.contains(listtenr)) {
            Log.i(TAG, "addListtner: ");
            listtenrList.add(listtenr);
            UsbChangeReciver.findUsbList();
            listtenr.usbInitList(UsbChangeReciver.currentBusList, UsbChangeReciver.devices);
        }
    }

    public void removeListtner(UsbStateListtenr listtenr) {
        Log.i(TAG, "addListtner: ");
        listtenrList.remove(listtenr);

    }
}

